/* Copyright 2011 Tobias Marschall, Email: tm@cwi.nl 
 * 
 * This file is part of string-cover.
 *
 * string-cover is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * string-cover is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with string-cover.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <cassert>
#include <iostream>
#include <boost/tokenizer.hpp>

#include "LengthBasedWeightFunction.h"

using namespace std;
using namespace boost;

LengthBasedWeightFunction::LengthBasedWeightFunction(auto_ptr<vector<double> > weight_by_length, bool is_integer, double default_weight) : weight_by_length(weight_by_length), is_integer(is_integer), default_weight(default_weight) {
}

LengthBasedWeightFunction::~LengthBasedWeightFunction() {
}

LengthBasedWeightFunction::LengthBasedWeightFunction(std::ifstream & f, double default_weight) : default_weight(default_weight){
	assert(f.is_open());
	weight_by_length = auto_ptr<vector<double> >(new vector<double>);
	is_integer = true;
	char_separator<char> sep(" \t");
	int n = 0;
	while(!f.eof()) {
		string s;
		getline(f, s);
		n += 1;
		if (s.empty()) continue;
		tokenizer<char_separator<char> > t(s, sep);
		vector<string> tokens(t.begin(), t.end());
		if (tokens.size()!=2) {
			cerr << "Error reading weight function from file. Offending line: " << n << endl;
			exit(1);
		}
		size_t length = atoi(tokens[0].c_str());
		double weight = atof(tokens[1].c_str());
		if (tokens[1].find(".") != string::npos) {
			is_integer = false;
		}
		while (weight_by_length->size()<=length) {
			weight_by_length->push_back(default_weight);
		}
		weight_by_length->at(length) = weight;
	}
	cout << "Read weight table: " << endl;
	for (size_t i=0; i<weight_by_length->size(); ++i) {
		cout << "  Length "<< i << ": " << weight_by_length->at(i) << endl;
	}
	cout << "Integer weights: " << (is_integer?"yes":"no") << endl;
}

bool LengthBasedWeightFunction::isInteger() const {
	return is_integer;
}

double LengthBasedWeightFunction::getWeight(std::string s) const {
	if (s.size()<weight_by_length->size()) return weight_by_length->at(s.size());
	else return default_weight;
}


